//
//  AirportViewController.swift
//  CitySearch
//
//  Created by guotonglin on 2020/6/3.
//  Copyright © 2020 guotonglin. All rights reserved.
//

import UIKit
import RxCocoa
import RxSwift
import RxDataSources

class AirportViewController: UIViewController, Storyboardable {

    @IBOutlet weak var tableView: UITableView!
    
    private var viewModel: AirportsViewPresentable!
    
    var viewModelBuilder: AirportsViewPresentable.ViewModelBuilder!
    
    private let bag = DisposeBag()
    
    static private let CellId = "AirportCell"
    
    private lazy var dataSource = RxTableViewSectionedReloadDataSource<AirportItemsSection>(configureCell: { _, tableView, indexPath, item in
        
        let cell = tableView.dequeueReusableCell(withIdentifier: AirportViewController.CellId, for: indexPath) as! AirportCell
        cell.configure(usingViewModel: item)
        return cell
    })
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.viewModel = self.viewModelBuilder((
            selectAirport: self.tableView.rx.modelSelected(AirportViewPresentable.self).asDriver(onErrorDriveWith: .empty()), ()
        ))
        
        self.setupUI()
        self.setupBinding()
    }
}

extension AirportViewController {
    
    func setupUI() {
        self.tableView.tableFooterView = UIView()
        self.tableView.register(UINib(nibName: "AirportCell", bundle: nil), forCellReuseIdentifier: AirportViewController.CellId)
    }
    
    func setupBinding() {
        self.viewModel.output.title
            .drive(self.rx.title)
            .disposed(by: bag)
        
        self.viewModel.output.airports
            .drive(self.tableView.rx.items(dataSource: self.dataSource))
            .disposed(by: bag)
    }
    
}
